# -*- coding: UTF-8 -*-
"""
 * @author  cyb233
 * @date  2021/1/9
"""
import argparse
import hashlib
import json
import logging
import os.path
import random
import re
import sys
import time
from urllib.parse import quote

import requests
from urllib3.exceptions import InsecureRequestWarning

import src.push as push

requests.urllib3.disable_warnings(InsecureRequestWarning)

LOG_FORMAT = "%(asctime)s - %(levelname)s - %(filename)s:%(lineno)s - %(funcName)s - %(message)s"
DATE_FORMAT = "%Y/%m/%d %H:%M:%S %p"
logging.basicConfig(level=logging.INFO,
                    format=LOG_FORMAT, datefmt=DATE_FORMAT)
print()
logging.debug('DEBUG 开启')

with open('configs/options.json', 'r') as e:
    options = json.load(e)

# API接口
API = 'https://api1.mimikko.cn/client/'
# 登录(post)
login_path = f'{API}user/LoginWithPayload'
is_sign = f'{API}user/GetUserSignedInformation'  # 今天是否签到
# history_path = f'{API}dailysignin/log/30/0'  # 签到历史
can_resign = f'{API}love/getcanresigntimes'  # 补签卡数量
defeat_set = f'{API}Servant/SetDefaultServant'  # 设置默认助手
# 补签(post)
resign_path = f'{API}love/resign?servantId='
sign_path = f'{API}RewardRuleInfo/SignAndSignInformationV3'  # 签到
energy_info_path = f'{API}love/GetUserServantInstance'  # 获取助手状态
energy_reward_path = f'{API}love/ExchangeReward'  # 兑换助手能量
vip_info = f'{API}user/GetUserVipInfo'  # 获取会员状态
vip_roll = f'{API}roll/RollReward'  # 会员抽奖(post)
# 会员每日领取(post)
vip_energy = f'{API}mission/ReceiveMemberLevelWelfare'
# 消费奖励列表
recharge_mission_api = f'{API}mission/GetUserUnionRechargeMissions'
# 消费奖励兑换(post)
exchange_mission_api = f'{API}mission/ExchangeMissions'
# sc_api = 'https://sc.ftqq.com/' #Server酱推送
# sct_api = 'https://sctapi.ftqq.com/' #Server酱推送Turbo版
# ding_api = 'https://oapi.dingtalk.com/robot/send?' # 钉钉推送
app_Version = '3.3.3'
app_id = 'wjB7LOP2sYkaMGLC'
servant_name = {
    'nonona': '诺诺纳',
    'momona': '梦梦奈',
    'ariana': '爱莉安娜',
    'miruku': '米璐库',
    'nemuri': '奈姆利',
    'ruri': '琉璃',
    'alpha0': '阿尔法零',
    'miruku2': '米露可',
    'ulrica': '优莉卡',
    'giwa': '羲和',
    'maya': '摩耶',
    'kuroko': '白井黑子',
    'mikoto': '御坂美琴',
    'kurumi': '胡桃',
    'kasutariri': '卡斯塔莉莉',
    'tamaki': '环古达',
    'alice': '爱丽丝'
}


def read_parser():
    try:
        parser = argparse.ArgumentParser(
            description='请从 登录账号(-u)和密码(-p) 或 AUTHORIZATION验证(-a) 中选择一种登录方式')
        # 还没用的: n, q, y, z
        parser.add_argument('-u', default=False,
                            metavar='ID', help='登录账号(邮箱或手机号)')
        parser.add_argument('-p', default=False,
                            metavar='password', help='登录密码')
        parser.add_argument('-a', default=False, metavar='Token',
                            help='AUTHORIZATION验证，抓包获取')
        parser.add_argument('-e', default=False,
                            metavar='code', help='助手代码，选择助手')
        parser.add_argument('-r', default=False,
                            metavar='resign', help='补签最近x天，可选数字1~7')
        parser.add_argument('-v', default=False,
                            metavar='max_favorability', help='最大好感度，达到时自动切换助手')
        parser.add_argument('-o', default=False,
                            metavar='award', help='是否兑换消费奖励')
        parser.add_argument('-s', default=False,
                            metavar='sckey', help='server酱推送密钥')
        parser.add_argument('-d', default=False,
                            metavar='token', help='钉钉机器人token')
        parser.add_argument('-c', default=False,
                            metavar='secret', help='钉钉机器人安全设置加签的secret')
        parser.add_argument('-i', default=False,
                            metavar='CompanyId', help='企业微信推送CompanyId')
        parser.add_argument('-x', default=False,
                            metavar='Secret', help='企业微信推送Secret')
        parser.add_argument('-w', default=False,
                            metavar='AgentId', help='企业微信推送AgentId')
        parser.add_argument('-b', default=False,
                            metavar='dc_webhook', help='Discord推送WebHook')
        parser.add_argument('-t', default=False,
                            metavar='tg_token', help='Telegram Bot Token')
        parser.add_argument('-g', default=False,
                            metavar='tg_id', help='你的Telegram id')
        parser.add_argument('-k', default=False,
                            metavar='pp_token', help='PushPlus推送Token')
        parser.add_argument('-f', default=False,
                            metavar='fs_token', help='飞书机器人token')
        parser.add_argument('-j', default=False,
                            metavar='fs_secret', help='飞书机器人安全设置加签的secret')
        parser.add_argument('-l', default=False,
                            metavar='misaka_position', help="MisakaNet服务器地址")

        parser.add_argument('-m', default=False,
                            metavar="misaka_key", help="MisakaNet misaka_key")

        parser.add_argument('-cs', default=False,
                            metavar="cache_server", help='Token缓存服务器')

        args = parser.parse_args()

        # 如果不带参数启动
        if len(sys.argv) < 2:
            if (os.path.isfile("configs/account.json")):
                logging.info('未指定任何参数，尝试从 configs/account.json 读取配置参数......')
                with open('configs/account.json', 'r') as f:
                    config = json.load(f)
            else:
                logging.info('未找到 configs/account.json 配置文件')
                parser.print_help()
                sys.exit(0)
        logging.info('正在获取secret参数')
        if len(sys.argv) < 2 and os.path.isfile("configs/account.json"):
            user_id = config["ID"]
            user_password = config["Password"]
            Authorization = config["Authorization"]
            Energy_code = config["Energy_code"]
            resign = config["resign"]
            max_favorability = config["max_favorability"]
            m_award = config["award"]
            sckey = config["sckey"]
            ding_token = config["ding_token"]
            ding_secret = config["ding_secret"]
            wx_agentid = config["wx_agentid"]
            wx_secret = config["wx_secret"]
            wx_companyid = config["wx_companyid"]
            dc_webhook = config["dc_webhook"]
            tg_token = config["tg_token"]
            tg_id = config["tg_id"]
            pp_token = config["pp_token"]
            fs_token = config["fs_token"]
            fs_secret = config["fs_secret"]
            misaka_position = config["misaka_position"]
            misaka_key = config["misaka_key"]
            cache_server = config["cache_server"]
        else:
            user_id = args.u
            user_password = args.p
            Authorization = args.a
            Energy_code = args.e
            resign = args.r
            max_favorability = args.v
            m_award = args.o
            sckey = args.s
            ding_token = args.d
            ding_secret = args.c
            wx_agentid = args.w
            wx_secret = args.x
            wx_companyid = args.i
            dc_webhook = args.b
            tg_token = args.t
            tg_id = args.g
            pp_token = args.k
            fs_token = args.f
            fs_secret = args.j
            misaka_position = args.l
            misaka_key = args.m
            cache_server = args.cs

        if user_id and user_id.strip():
            user_id = user_id.strip()
            logging.info('user_id 存在')
            # logging.debug(user_id)
        else:
            user_id = False
            logging.info('user_id 不存在')
        if user_password and user_password.strip():
            user_password = user_password.strip()
            logging.info('user_password 存在')
            # logging.debug(user_password)
        else:
            user_password = False
            logging.info('user_password 不存在')
        if Authorization and Authorization.strip():
            Authorization = Authorization.strip()
            logging.info('Authorization 存在')
            # logging.debug(Authorization)
        elif (user_id and user_password):
            Authorization = False
        else:
            Authorization = False
            logging.info('Authorization 不存在')
        if not ((user_id and user_password) or Authorization):
            logging.critical('获取参数错误：请在Secret中保存 登录ID和密码 或 Authorization ！！！')
            parser.print_usage()
            sys.exit(1)
        if Energy_code and Energy_code.strip():
            Energy_code = Energy_code.strip()
            logging.info('Energy_code 存在')
        else:
            Energy_code = 'momona'
        logging.debug(Energy_code)
        if resign and resign.strip():
            resign = int(resign.strip())
            if resign > 30:
                resign = 30
            elif resign < 1:
                resign = False
            if resign:
                logging.info('resign 存在')
                logging.debug(resign)
        else:
            resign = False
        if max_favorability and max_favorability.strip():
            max_favorability = int(max_favorability.strip())
            logging.info('max_favorability 存在')
        else:
            max_favorability = 136000
        logging.debug(max_favorability)
        if m_award and m_award.strip():
            m_award = True
            logging.info('m_award开启')
        else:
            m_award = False
        if sckey and sckey.strip():
            sckey = sckey.strip()
            logging.info('sckey 存在')
            # logging.debug(sckey)
        else:
            sckey = False
        if ding_token and ding_token.strip():
            if ding_token and ding_token.find('access_token=') != -1:
                ding_token = ding_token[ding_token.find('access_token=') + 13:]
            ding_token = ding_token.strip()
            logging.info('ding_token 存在')
            # logging.debug(ding_token)
        else:
            ding_token = False
        if ding_secret and ding_secret.strip():
            ding_secret = ding_secret.strip()
            logging.info('ding_secret 存在')
            # logging.debug(ding_secret)
        else:
            ding_secret = False
        if wx_agentid and wx_agentid.strip():
            wx_agentid = wx_agentid.strip()
            logging.info('wx_agentid 存在')
            # logging.debug(wx_agentid)
        else:
            wx_agentid = False
        if wx_secret and wx_secret.strip():
            wx_secret = wx_secret.strip()
            logging.info('wx_secret 存在')
            # logging.debug(wx_secret)
        else:
            wx_secret = False
        if wx_companyid and wx_companyid.strip():
            wx_companyid = wx_companyid.strip()
            logging.info('wx_companyid 存在')
            # logging.debug(wx_companyid)
        else:
            wx_companyid = False
        if dc_webhook and dc_webhook.strip():
            dc_webhook = dc_webhook.strip()
            logging.info('dc_webhook 存在')
            # logging.debug(dc_webhook)
        else:
            dc_webhook = False
        if tg_token and tg_token.strip():
            tg_token = tg_token.strip()
            logging.info('tg_token 存在')
            # logging.debug(tg_token)
        else:
            tg_token = False
        if tg_id and tg_id.strip():
            tg_id = tg_id.strip()
            logging.info('tg_id 存在')
            # logging.debug(tg_id)
        else:
            tg_id = False
        if pp_token and pp_token.strip():
            pp_token = pp_token.strip()
            logging.info('pp_token 存在')
            # logging.debug(pp_token)
        else:
            pp_token = False
        if fs_token and fs_token.strip():
            if fs_token and fs_token.find('/hook/') != -1:
                fs_token = fs_token[fs_token.find('/hook/') + 6:]
            fs_token = fs_token.strip()
            logging.info('fs_token 存在')
            # logging.debug(fs_token)
        else:
            fs_token = False
        if fs_secret and fs_secret.strip():
            fs_secret = fs_secret.strip()
            logging.info('fs_secret 存在')
            # logging.debug(fs_secret)
        else:
            fs_secret = False
        if misaka_position and misaka_position.strip():
            misaka_position = misaka_position.strip()
            logging.info("misaka_position 存在")
            # logging.debug(misaka_position)
        else:
            misaka_position = False
        if misaka_key and misaka_key.strip():
            misaka_key = misaka_key.strip()
            logging.info("misaka_key 存在")
            # logging.debug(misaka_key)
        else:
            misaka_key = False
        if cache_server and cache_server.strip():
            cache_server = cache_server.strip()
            logging.info("cache_server 存在")
            # logging.debug(cache_server)
        else:
            cache_server = False

        logging.info('获取参数结束')
        if sckey:
            push_set1 = 'Server酱, '
        else:
            push_set1 = False
        if (ding_token and ding_secret):
            push_set2 = '钉钉, '
        else:
            push_set2 = False
        if (wx_agentid and wx_secret and wx_companyid):
            push_set3 = '企业微信, '
        else:
            push_set3 = False
        if dc_webhook:
            push_set4 = 'Discord, '
        else:
            push_set4 = False
        if pp_token:
            push_set5 = 'pp_token, '
        else:
            push_set5 = False
        if fs_token and fs_secret:
            push_set6 = '飞书, '
        else:
            push_set6 = False
        if tg_token and tg_id:
            push_set7 = 'Telegram, '
        else:
            push_set7 = False
        if misaka_position and misaka_key:
            push_set8 = 'misakaNet, '
        else:
            push_set8 = False
    except Exception as es:
        logging.critical(es, exc_info=True)
        parser.print_usage()
        # sys.exit(1)

    return user_id, user_password, Authorization, Energy_code, resign, m_award, sckey, ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, dc_webhook, tg_token, tg_id, pp_token, fs_token, fs_secret, misaka_position, misaka_key, push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8, cache_server, max_favorability


def mimikko():
    logging.info('脚本开始')
    global Authorization
    user_id, user_password, Authorization, Energy_code, resign, m_award, sckey, ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, dc_webhook, tg_token, tg_id, pp_token, fs_token, fs_secret, misaka_position, misaka_key, push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8, cache_server, max_favorability = read_parser()
    # 登录
    logging.info('开始登录')
    if user_id and user_password:
        logging.info("使用 ID密码 登录")
        user_password_sha = hashlib.sha256(
            user_password.encode('utf-8')).hexdigest()
        login_data = push.mimikko_login(login_path, app_id, app_Version, {"password": user_password_sha, "id": user_id},
                                        cache_server)
        # logging.debug(login_data)
        if login_data and login_data.get('body'):
            if login_data["code"] == '0':
                Authorization = login_data["body"]["Token"]
            else:
                logging.warning("登录错误，请检查账号和密码是否正确")
                dddata, scdata, wxdata, dcdata, tgdata, ppdata, fsdata, misakadata = push.AllPush(
                    ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, sckey, dc_webhook, tg_token, tg_id,
                    pp_token, fs_token, fs_secret, misaka_position, misaka_key, "兽耳助手签到登录错误", "兽耳助手登录错误，请检查账号和密码是否正确")
                push.push_check(push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8,
                                dddata, scdata,
                                wxdata, dcdata, tgdata, ppdata, fsdata, misakadata)
                logging.critical('兽耳助手登录错误！！！')
                sys.exit(1)
        if Authorization:
            logging.info("登录成功！")
        else:
            logging.warning("登录错误")
            dddata, scdata, wxdata, dcdata, tgdata, ppdata, fsdata, misakadata = push.AllPush(
                ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, sckey, dc_webhook, tg_token, tg_id,
                pp_token, fs_token, fs_secret, misaka_position, misaka_key, "兽耳助手签到登录错误", "兽耳助手登录错误，请访问GitHub检查")
            push.push_check(push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8,
                            dddata, scdata,
                            wxdata, dcdata, tgdata, ppdata, fsdata, misakadata)
            logging.critical('兽耳助手登录错误！！！')
            sys.exit(1)
    else:
        if Authorization:
            logging.info("使用 Authorization 验证")
        else:
            dddata, scdata, wxdata, dcdata, tgdata, ppdata, fsdata, misakadata = push.AllPush(
                ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, sckey, dc_webhook, tg_token, tg_id,
                pp_token, fs_token, fs_secret, misaka_position, misaka_key, "兽耳助手签到登录错误",
                "登录错误，未找到 Authorization ，请访问GitHub检查")
            push.push_check(push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8,
                            dddata, scdata,
                            wxdata, dcdata, tgdata, ppdata, fsdata, misakadata)
            logging.critical('请在Secret中保存 登录ID和密码 或 Authorization ！！！')
            sys.exit(1)
    # 设置默认助手
    time.sleep(random.randint(1, 3))
    logging.info(f'设置默认助手{servant_name[Energy_code]}')
    defeat_servant = push.mimikko_get(
        f'{defeat_set}?code={Energy_code}', app_id, app_Version, Authorization, "")
    logging.debug(defeat_servant)
    # 执行前的好感度
    time.sleep(random.randint(1, 3))
    original_energy_data = push.mimikko_get(
        f'{energy_info_path}?code={Energy_code}', app_id, app_Version, Authorization, "")
    logging.debug(original_energy_data)
    if original_energy_data and original_energy_data.get('body'):
        original_energy_post = str(
            original_energy_data["body"]["Favorability"])
    else:
        original_energy_post = "Error"
    logging.info(f'执行前的好感度{original_energy_post}')
    if max_favorability > 0:
        if int(original_energy_post) >= max_favorability:
            for each_code in servant_name.keys():
                each_name = servant_name[each_code]
                logging.info(
                    f'助手{servant_name[Energy_code]}好感度已经达标({original_energy_post}/{max_favorability}),切换下一个助手{each_name}')
                Energy_code = each_code
                # 设置默认助手
                time.sleep(random.randint(1, 3))
                logging.info(f'设置默认助手{servant_name[Energy_code]}')
                defeat_servant = push.mimikko_get(
                    f'{defeat_set}?code={Energy_code}', app_id, app_Version, Authorization, "")
                logging.debug(defeat_servant)
                # 执行前的好感度
                time.sleep(random.randint(1, 3))
                original_energy_data = push.mimikko_get(
                    f'{energy_info_path}?code={Energy_code}', app_id, app_Version, Authorization, "")
                logging.debug(original_energy_data)
                if original_energy_data and original_energy_data.get('body'):
                    original_energy_post = str(
                        original_energy_data["body"]["Favorability"])
                else:
                    original_energy_post = "Error"
                logging.info(f'执行前的好感度{original_energy_post}')
                if int(original_energy_post) < max_favorability:
                    break
    # 签到历史
    # time.sleep(random.randint(1, 3))
    # logging.info('正在获取签到历史')
    # sign_history = push.mimikko_get(
    #     history_path, app_id, app_Version, Authorization, "")
    # logging.debug(sign_history)
    # signLogs = sign_history["body"]["signLogs"]
    # 执行前的签到日
    time.sleep(random.randint(1, 3))
    old_sign_info = push.mimikko_get(
        is_sign, app_id, app_Version, Authorization, "")
    logging.debug(old_sign_info)
    # 补签
    if resign and old_sign_info and old_sign_info["body"]["ContinuousSignDays"] < resign:
        logging.info("正在尝试补签")
        # 补签前的补签卡
        time.sleep(random.randint(1, 3))
        cansign_before = push.mimikko_get(
            can_resign, app_id, app_Version, Authorization, "")
        logging.debug(cansign_before)
        if cansign_before and cansign_before.get('body'):
            cansign_before_time = cansign_before["body"]["Value"]
        else:
            cansign_before_time = False
        logging.info(f'补签前的补签卡：{cansign_before_time}')
        for i in range(1, resign+1):
            if old_sign_info["body"]["ContinuousSignDays"] <= i <= resign:
                logging.info(f'向前第 {i} 天')
                resign_time = int(time.time()) - 86400 * i
                r_date = push.timeStamp1time(resign_time)
                time.sleep(random.randint(1, 3))
                resign_data = push.mimikko_post(
                    resign_path, app_id, app_Version, Authorization, f'["{r_date}T15:59:59+0800"]')
                logging.debug(resign_data)
                if resign_data and resign_data["code"] == 0:
                    logging.info("补签成功")
                else:
                    logging.info("未补签")
            else:
                break
        # 补签后的补签卡
        time.sleep(random.randint(1, 3))
        cansign_after = push.mimikko_get(
            can_resign, app_id, app_Version, Authorization, "")
        logging.debug(cansign_after)
        if cansign_after and cansign_after.get('body'):
            cansign_after_time = cansign_after["body"]["Value"]
        else:
            cansign_after_time = False
        logging.info(f'补签后的补签卡：{cansign_after_time}')
        # 使用的补签卡
        if cansign_before_time and cansign_after_time:
            times_resigned = cansign_after_time - cansign_before_time
        else:
            times_resigned = False
        logging.info(f'消耗 {times_resigned} 张')
    else:
        times_resigned = False
    # 签到
    time.sleep(random.randint(1, 3))
    logging.info('正在尝试签到')
    sign_data = push.mimikko_get(
        sign_path, app_id, app_Version, Authorization, "")
    logging.debug(sign_data)
    if sign_data and sign_data.get('body'):
        time.sleep(random.randint(1, 3))
        sign_info = push.mimikko_get(
            is_sign, app_id, app_Version, Authorization, "")
        logging.debug(sign_info)
        if sign_data["body"]["GetExp"]:
            if times_resigned:
                sign_result_post = f'''补签成功{str(times_resigned)}/{str(resign)}天\n签到成功：{str(sign_info["body"]["ContinuousSignDays"])}天\n好感度：{str(sign_data["body"]["Reward"])}\n硬币：{str(sign_data["body"]["GetCoin"])}\n经验值：{str(sign_data["body"]["GetExp"])}\n签到卡片：{sign_data["body"]["Description"]}{sign_data["body"]["Name"]}\n{sign_data["body"]["PictureUrl"]}'''
            else:
                sign_result_post = f'''签到成功：{str(sign_info["body"]["ContinuousSignDays"])}天\n好感度：{str(sign_data["body"]["Reward"])}\n硬币：{str(sign_data["body"]["GetCoin"])}\n经验值：{str(sign_data["body"]["GetExp"])}\n签到卡片：{sign_data["body"]["Description"]}{sign_data["body"]["Name"]}\n{sign_data["body"]["PictureUrl"]}'''
            title_ahead = f'''兽耳助手签到{str(sign_info["body"]["ContinuousSignDays"])}'''
        else:
            sign_result_post = f'''今日已签到：{str(sign_info["body"]["ContinuousSignDays"])}天\n签到卡片：{sign_data["body"]["Description"]}{sign_data["body"]["Name"]}\n{sign_data["body"]["PictureUrl"]}'''
            title_ahead = f'''兽耳助手签到{str(sign_info["body"]["ContinuousSignDays"])}'''
    else:
        sign_result_post = '签到失败'
        title_ahead = '兽耳助手签到'
    logging.info(title_ahead)
    # VIP抽奖
    time.sleep(random.randint(1, 3))
    logging.info('正在尝试VIP抽奖')
    vip_info_data = push.mimikko_get(
        vip_info, app_id, app_Version, Authorization, "")
    logging.debug(vip_info_data)
    if vip_info_data and vip_info_data.get('body'):
        if vip_info_data["body"]["rollNum"] > 0:
            time.sleep(random.randint(1, 3))
            vip_roll_data = push.mimikko_post(
                vip_roll, app_id, app_Version, Authorization, "")
            logging.debug(vip_roll_data)
            if vip_roll_data["body"]["Value"]["message"] is None:
                vip_roll_msg = f'''VIP抽奖成功：{vip_roll_data["body"]["Value"]["description"]}'''
            else:
                vip_roll_msg = f'''VIP抽奖失败：{vip_roll_data["body"]["Value"]["message"]}'''
        else:
            vip_roll_data = "抽奖次数不足"
            if vip_info_data["body"]["isValid"]:
                vip_roll_msg = "VIP抽奖失败：今天已经抽过奖了"
            else:
                vip_roll_msg = "VIP抽奖失败：您还不是VIP"
        if vip_info_data["body"]["isValid"]:
            time.sleep(random.randint(1, 3))
            vip_energy_data = push.mimikko_post(
                vip_energy, app_id, app_Version, Authorization, "")
            logging.debug(vip_energy_data)
            if vip_energy_data["ok"]:
                vip_energy_msg = f'''VIP能量领取成功：{vip_energy_data["body"]["Value"]["message"]}'''
            else:
                vip_energy_msg = f'''VIP能量领取失败：{vip_energy_data["msg"]}'''
        else:
            vip_energy_msg = "VIP能量领取失败：您还不是VIP"
        vip_roll_post = f'''{vip_roll_msg}\n{vip_energy_msg}'''
    else:
        vip_roll_data = "VIP信息获取失败"
        vip_roll_post = "VIP信息获取失败，未抽奖和领取能量"
    logging.info(vip_roll_msg)
    logging.info(vip_energy_msg)
    # 能量兑换好感度
    logging.info('正在尝试兑换能量')
    if not original_energy_data:
        time.sleep(random.randint(1, 3))
        original_energy_data = push.mimikko_get(
            f'{energy_info_path}?code={Energy_code}', app_id, app_Version, Authorization, "")
        logging.debug(original_energy_data)
    if original_energy_data and original_energy_data.get('body'):
        if original_energy_data["body"]["Energy"] > 0:
            time.sleep(random.randint(1, 3))
            energy_reward_data = push.mimikko_get(
                f'{energy_reward_path}?code={Energy_code}', app_id, app_Version, Authorization, "")
            logging.debug(energy_reward_data)
            gethgd = int(
                energy_reward_data["body"]["Favorability"]) - int(original_energy_post)
            energy_reward_post = f'''能量值：{str(original_energy_data["body"]["Energy"])}/{str(original_energy_data["body"]["MaxEnergy"])}\n好感度兑换成功\n助手：{servant_name[energy_reward_data["body"]["code"]]} LV{str(energy_reward_data["body"]["Level"])} +{gethgd}({original_energy_post}→{str(energy_reward_data["body"]["Favorability"])}/{str(original_energy_data["body"]["MaxFavorability"])})'''
            logging.info('兑换成功')
            title_post = f'''{title_ahead}{servant_name[original_energy_data["body"]["code"]]}好感度{str(energy_reward_data["body"]["Favorability"])}'''
        else:
            energy_reward_data = "您的能量值不足，无法兑换"
            gethgd = int(
                original_energy_data["body"]["Favorability"]) - int(original_energy_post)
            energy_reward_post = f'''能量值：{str(original_energy_data["body"]["Energy"])}/{str(original_energy_data["body"]["MaxEnergy"])}\n好感度兑换失败：当前没有能量\n助手：{servant_name[original_energy_data["body"]["code"]]} LV{str(original_energy_data["body"]["Level"])} +{gethgd}({original_energy_post}→{str(original_energy_data["body"]["Favorability"])}/{str(original_energy_data["body"]["MaxFavorability"])})'''
            logging.info(energy_reward_data)
            title_post = f'''{title_ahead}{servant_name[original_energy_data["body"]["code"]]}好感度{str(original_energy_data["body"]["Favorability"])}'''
    else:
        energy_reward_data = "能量兑换失败"
        title_post = title_ahead
        gethgd = 0
        energy_reward_post = "能量兑换失败"
        logging.info(energy_reward_data)
    # 查询和兑换奖品
    exchange_message = '\n'
    if m_award:
        logging.info('正在查询和兑换奖品')
        exchange_message = '\n兑换了：'
        time.sleep(random.randint(1, 3))
        recharge_mission_data = push.mimikko_get(
            recharge_mission_api, app_id, app_Version, Authorization, "")
        logging.debug(recharge_mission_data)
        if recharge_mission_data and recharge_mission_data["code"] == '0':
            # 消费阶段奖励
            recharge_mission_data_rewards = recharge_mission_data["body"]["rewards"]
            logging.debug(recharge_mission_data_rewards)
            # 累计消费奖品
            recharge_mission_data_exchanges = recharge_mission_data["body"]["exchanges"]
            logging.debug(recharge_mission_data_exchanges)
            for reward in recharge_mission_data_rewards:
                logging.debug(reward)
                if reward["exchangeable"] and not reward["exchanged"]:
                    logging.info(f'尝试兑换了{reward["name"]}')
                    time.sleep(random.randint(1, 3))
                    reward_id = quote(reward["id"])
                    exchange_result = push.mimikko_post(
                        exchange_mission_api, app_id, app_Version, Authorization, f'missionId={reward_id}', 'application/x-www-form-urlencoded')
                    if exchange_result and exchange_result["code"] == '0' and exchange_result["body"]["Value"]["success"]:
                        exchange_message = f'{exchange_message}{reward["name"]}，'
            for reward in recharge_mission_data_exchanges:
                # logging.debug(reward)
                if reward["exchangeable"] and not reward["exchanged"]:
                    logging.info(f'尝试兑换了{reward["name"]}')
                    time.sleep(random.randint(1, 3))
                    reward_id = quote(reward["id"])
                    exchange_result = push.mimikko_post(
                        exchange_mission_api, app_id, app_Version, Authorization, f'missionId={reward_id}', 'application/x-www-form-urlencoded')
                    if exchange_result and exchange_result["code"] == '0' and exchange_result["body"]["Value"]["success"]:
                        exchange_message = f'{exchange_message}{reward["name"]}，'
            if exchange_message == '\n兑换了：':
                exchange_message = '\n没有可兑换的消费奖励\n'
            else:
                exchange_message = exchange_message.strip('，')
                exchange_message = f'{exchange_message}\n'
    logging.info('脚本结束')
    return sign_data, vip_info_data, vip_roll_data, original_energy_data, energy_reward_data, sign_info, sign_result_post, title_post, vip_roll_post, energy_reward_post, exchange_message, user_id, user_password, Authorization, Energy_code, resign, sckey, ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, dc_webhook, tg_token, tg_id, pp_token, fs_token, fs_secret, misaka_position, misaka_key, push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8


def main():
    try:
        sign_data, vip_info_data, vip_roll_data, original_energy_data, energy_reward_data, sign_info, sign_result_post, title_post, vip_roll_post, energy_reward_post, exchange_message, user_id, user_password, Authorization, Energy_code, resign, sckey, ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, dc_webhook, tg_token, tg_id, pp_token, fs_token, fs_secret, misaka_position, misaka_key, push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8 = mimikko()
        varErr = True
        varErrText = ''
        for i in ['sign_data', 'vip_info_data', 'vip_roll_data', 'original_energy_data', 'energy_reward_data',
                  'sign_info', 'sign_result_post', 'title_post', 'vip_roll_post', 'energy_reward_post']:
            if not i in locals():
                varErr = False
                logging.warning(f'{i} 缺失')
                varErrText = f'{varErrText},{i}'
        if varErr:
            now_time = push.timeStamp2time(time.time() + 28800)
            post_text = re.sub(
                '\\n', '  \n',
                f'现在是：{now_time}\n{sign_result_post}\n{vip_roll_post}\n{energy_reward_post}{exchange_message}签到版本：{app_Version}')
        else:
            varErrText = f'函数返回值 {varErrText[1:]} 缺失'
    except Exception as em:
        varErr = False
        varErrText = f'Error: {em}'
        logging.critical(em, exc_info=True)

    try:
        if varErr:
            logging.info("运行成功，正在推送")
            dddata, scdata, wxdata, dcdata, tgdata, ppdata, fsdata, misakadata = push.AllPush(
                ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, sckey, dc_webhook, tg_token, tg_id,
                pp_token, fs_token, fs_secret, misaka_position, misaka_key, title_post, post_text)
            push.push_check(push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8,
                            dddata, scdata,
                            wxdata, dcdata, tgdata, ppdata, fsdata, misakadata)
            push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8 = push.push_set_check(
                push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8, dddata, scdata,
                wxdata, dcdata, tgdata, ppdata, fsdata, misakadata)
            logging.info(f'All Finish!\n\n推送信息：\n\n{title_post}\n{post_text}')
        else:
            logging.warning("运行失败，正在推送")
            logging.warning(f"兽耳助手签到数据异常，请访问GitHub检查：“{varErrText}”")
            dddata, scdata, wxdata, dcdata, tgdata, ppdata, fsdata, misakadata = push.AllPush(
                ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, sckey, dc_webhook, tg_token, tg_id,
                pp_token, fs_token, fs_secret, misaka_position, misaka_key, "兽耳助手签到数据异常",
                f'兽耳助手签到数据异常，请访问GitHub检查：“{varErrText}”')
            push.push_check(push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8,
                            dddata, scdata,
                            wxdata, dcdata, tgdata, ppdata, fsdata, misakadata)
            push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8 = push.push_set_check(
                push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8, dddata, scdata,
                wxdata, dcdata, tgdata, ppdata, fsdata, misakadata)
    except Exception as es:
        logging.warning("数据异常，尝试推送")
        if not push_set1:
            sckey = False
        if not push_set2:
            ding_token = ding_secret = False
        if not push_set3:
            wx_agentid = wx_secret = wx_companyid = False
        if not push_set4:
            dc_webhook = False
        if not push_set5:
            pp_token = False
        if not push_set6:
            fs_token = fs_secret = False
        dddata, scdata, wxdata, dcdata, tgdata, ppdata, fsdata, misakadata = push.AllPush(
            ding_token, ding_secret, wx_agentid, wx_secret, wx_companyid, sckey, dc_webhook, tg_token, tg_id, pp_token,
            fs_token, fs_secret, misaka_position, misaka_key, "兽耳助手签到数据异常", f"兽耳助手签到数据异常，请访问GitHub检查：{es}")
        push.push_check(push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8, dddata,
                        scdata,
                        wxdata, dcdata, tgdata, ppdata, fsdata, misakadata)
        push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8 = push.push_set_check(
            push_set1, push_set2, push_set3, push_set4, push_set5, push_set6, push_set7, push_set8, dddata, scdata,
            wxdata, dcdata, tgdata, ppdata, fsdata, misakadata)
        logging.error(es, exc_info=True)

    # if push_set1 or push_set2 or push_set3 or push_set4 or push_set5 or push_set6 or push_set7 or push_set8:
    # logging.warning(re.sub(',  ', ' ', re.sub( 'False', '', f'{push_set1}{push_set2}{push_set3}{push_set4}{
    # push_set5}{push_set6}{push_set7}{push_set8} 推送异常，请检查'))) sys.exit(2)
    return


if options["isServerless"] == "False":
    main()
